package com.atguigu.gmall.rest;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.cart.entity.CartInfo;
import com.atguigu.gmall.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author:lyd
 **/
@RestController
@RequestMapping("/api/cart")
public class CartRestController {

    @Autowired
    CartService cartService;

    /**
     * 1、这是对/cartList 请求的补充，当购物车合并超限出错时，给前端响应224
     * 2、前端收到非200的码，给用户提示错误。再发一个请求，只要用户当前购物车数据 /userCartList
     * @return
     */
    @GetMapping("/userCartList")
    public Result userCartList(){

        String cartKey = cartService.determineCartKey();
        List<CartInfo> infos = cartService.userList(cartKey);
        return Result.ok(infos);
    }


    /**
     * 获取购物车列表，这个请求在合并购物车时可能会出现错误，导致无法获取购物车列表
     * @return
     */
    @GetMapping("/cartList")
    public Result cartList() {
        String cartKey = cartService.determineCartKey();
        List<CartInfo> cartList = cartService.cartList(cartKey);
        return Result.ok(cartList);
    }

    @GetMapping("/checkCart/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable("skuId") Long skuId,
                            @PathVariable("isChecked") Integer isChecked) {
        String cartKey = cartService.determineCartKey();
        cartService.checkCart(cartKey,skuId, isChecked);
        return Result.ok();
    }

    @DeleteMapping("/deleteCart/{skuId}")
    public Result deleteCartBySkuId(@PathVariable("skuId") Long skuId) {
        String cartKey = cartService.determineCartKey();
        cartService.deleteCartBySkuId(cartKey,skuId);
        return Result.ok();
    }
    @PostMapping("/addToCart/{skuId}/{num}")
    public Result addToCart(@PathVariable("skuId") Long skuId,
                           @PathVariable("num") Long num) {
        String cartKey = cartService.determineCartKey();
        cartService.incrOrDecr(cartKey,skuId,num);
        return Result.ok();
    }
}
